<template>
  <div class="login-view">
    <h1 class="login-title">南通评估系统</h1>
    
    <a-form
      :model="loginForm"
      :rules="loginRules"
      @finish="handleSubmit"
      class="login-form"
    >
      <a-form-item name="username">
        <a-input 
          v-model:value="loginForm.username"
          placeholder="请输入用户名"
          size="large"
        >
          <template #prefix>
            <UserOutlined />
          </template>
        </a-input>
      </a-form-item>
      
      <a-form-item name="password">
        <a-input-password
          v-model:value="loginForm.password"
          placeholder="请输入密码"
          size="large"
        >
          <template #prefix>
            <LockOutlined />
          </template>
        </a-input-password>
      </a-form-item>
      
      <a-form-item name="captcha" v-if="showCaptcha">
        <div class="captcha-container">
          <a-input
            v-model:value="loginForm.code"
            placeholder="请输入验证码"
            size="large"
          >
            <template #prefix>
              <SafetyOutlined />
            </template>
          </a-input>
          <div class="captcha-image" @click="refreshCaptcha">
            <img :src="captchaUrl" alt="验证码" />
          </div>
        </div>
      </a-form-item>
      
      <a-form-item>
        <a-button
          type="primary"
          html-type="submit"
          size="large"
          :loading="loading"
          block
        >
          登录
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { UserOutlined, LockOutlined, SafetyOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { setToken, setUserInfo } from '@/utils/auth'
import { request } from '@/utils/request'
import type { LoginResultDTO } from '@/types/auth'

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: '',
  code: '',
  uuid: ''
})

// 表单验证规则
const loginRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
}

// 是否显示验证码
const showCaptcha = ref(false)
// 验证码URL
const captchaUrl = ref('')
// 验证码UUID
const uuid = ref('')
// 加载状态
const loading = ref(false)
// 路由
const router = useRouter()

// 获取验证码
const getCaptcha = () => {
  const timestamp = new Date().getTime()
  uuid.value = `captcha-${timestamp}`
  captchaUrl.value = `/api/auth/captcha?uuid=${uuid.value}&t=${timestamp}`
}

// 刷新验证码
const refreshCaptcha = () => {
  if (showCaptcha.value) {
    getCaptcha()
  }
}

// 表单提交
const handleSubmit = async () => {
  try {
    loading.value = true

    // 调用登录接口
    const result = await request<LoginResultDTO>({
      url: '/auth/login',
      method: 'post',
      data: loginForm
    })

    // 保存令牌到localStorage
    setToken(result.accessToken)
    
    // 保存用户信息
    if (result.userInfo) {
      setUserInfo(result.userInfo)
    }
    
    message.success('登录成功')
    
    // 获取重定向地址，如果有的话
    const redirect = router.currentRoute.value.query?.redirect as string
    router.push(redirect || '/')
  } catch (error: any) {
    console.error('登录失败:', error)
    message.error(error.message || '登录失败')
    
    // 登录失败后显示验证码
    if (!showCaptcha.value) {
      showCaptcha.value = true
      getCaptcha()
    } else {
      refreshCaptcha()
    }
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-view {
  width: 100%;
}

.login-title {
  text-align: center;
  margin-bottom: 30px;
  color: #1890ff;
  font-size: 28px;
}

.login-form {
  width: 100%;
}

.captcha-container {
  display: flex;
  gap: 10px;
}

.captcha-image {
  width: 100px;
  height: 40px;
  cursor: pointer;
}

.captcha-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>